const db = require('../config/database');
const logger = require('../utils/logger');

class ProductController {
  // 获取商品列表（前台）
  async getProducts(req, res) {
    try {
      const { category_id, keyword, page = 1, pageSize = 20 } = req.query;
      const offset = (page - 1) * pageSize;

      let sql = `SELECT p.*, c.name as category_name 
                 FROM products p 
                 LEFT JOIN product_categories c ON p.category_id = c.id 
                 WHERE p.status = 1`;
      const params = [];

      if (category_id) {
        sql += ' AND p.category_id = ?';
        params.push(category_id);
      }

      if (keyword) {
        sql += ' AND (p.name LIKE ? OR p.description LIKE ?)';
        const likeKeyword = `%${keyword}%`;
        params.push(likeKeyword, likeKeyword);
      }

      sql += ' ORDER BY p.id DESC LIMIT ? OFFSET ?';
      params.push(parseInt(pageSize), offset);

      const [products] = await db.query(sql, params);

      // 处理图片字段：如果是JSON字符串，解析为数组；如果是单个URL，转为数组
      products.forEach(product => {
        if (product.image) {
          try {
            const parsed = JSON.parse(product.image);
            product.image = Array.isArray(parsed) ? parsed : [parsed];
          } catch {
            // 不是JSON，单个URL转为数组
            product.image = [product.image];
          }
        } else {
          product.image = [];
        }
      });

      // 获取总数
      let countSql = 'SELECT COUNT(*) as total FROM products WHERE status = 1';
      const countParams = [];

      if (category_id) {
        countSql += ' AND category_id = ?';
        countParams.push(category_id);
      }

      if (keyword) {
        countSql += ' AND (name LIKE ? OR description LIKE ?)';
        const likeKeyword = `%${keyword}%`;
        countParams.push(likeKeyword, likeKeyword);
      }

      const [countResult] = await db.query(countSql, countParams);

      res.json({
        success: true,
        data: {
          list: products,
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      logger.error('获取商品列表失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 获取商品详情（前台）
  async getProductDetail(req, res) {
    const { id } = req.params;

    try {
      const [products] = await db.query(
        `SELECT p.*, c.name as category_name 
         FROM products p 
         LEFT JOIN product_categories c ON p.category_id = c.id 
         WHERE p.id = ?`,
        [id]
      );

      if (products.length === 0) {
        return res.json({ success: false, message: '商品不存在' });
      }

      const product = products[0];

      // 处理图片字段：如果是JSON字符串，解析为数组；如果是单个URL，转为数组
      if (product.image) {
        try {
          const parsed = JSON.parse(product.image);
          product.image = Array.isArray(parsed) ? parsed : [parsed];
        } catch {
          // 不是JSON，单个URL转为数组
          product.image = [product.image];
        }
      } else {
        product.image = [];
      }

      // 增加浏览次数（可选）
      // await db.query('UPDATE products SET views = views + 1 WHERE id = ?', [id]);

      res.json({
        success: true,
        data: product
      });
    } catch (error) {
      logger.error('获取商品详情失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 获取商品列表（后台管理）
  async getProductsAdmin(req, res) {
    try {
      const { category_id, status, keyword, page = 1, pageSize = 10 } = req.query;
      const offset = (page - 1) * pageSize;

      let sql = `SELECT p.*, c.name as category_name 
                 FROM products p 
                 LEFT JOIN product_categories c ON p.category_id = c.id 
                 WHERE 1=1`;
      const params = [];

      if (category_id) {
        sql += ' AND p.category_id = ?';
        params.push(category_id);
      }

      if (status !== undefined) {
        sql += ' AND p.status = ?';
        params.push(status);
      }

      if (keyword) {
        sql += ' AND (p.name LIKE ? OR p.description LIKE ?)';
        const likeKeyword = `%${keyword}%`;
        params.push(likeKeyword, likeKeyword);
      }

      sql += ' ORDER BY p.id DESC LIMIT ? OFFSET ?';
      params.push(parseInt(pageSize), offset);

      const [products] = await db.query(sql, params);

      // 处理图片字段：如果是JSON字符串，解析为数组；如果是单个URL，转为数组
      products.forEach(product => {
        if (product.image) {
          try {
            const parsed = JSON.parse(product.image);
            product.image = Array.isArray(parsed) ? parsed : [parsed];
          } catch {
            // 不是JSON，单个URL转为数组
            product.image = [product.image];
          }
        } else {
          product.image = [];
        }
      });

      // 获取总数
      let countSql = 'SELECT COUNT(*) as total FROM products WHERE 1=1';
      const countParams = [];

      if (category_id) {
        countSql += ' AND category_id = ?';
        countParams.push(category_id);
      }

      if (status !== undefined) {
        countSql += ' AND status = ?';
        countParams.push(status);
      }

      if (keyword) {
        countSql += ' AND (name LIKE ? OR description LIKE ?)';
        const likeKeyword = `%${keyword}%`;
        countParams.push(likeKeyword, likeKeyword);
      }

      const [countResult] = await db.query(countSql, countParams);

      res.json({
        success: true,
        data: {
          list: products,
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      logger.error('获取商品列表失败（后台）', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 创建商品（后台管理）
  async createProduct(req, res) {
    try {
      let { name, description, detail, price, category_id, image, images, stock = -1, is_virtual = 1, delivery_method = 'auto', download_url } = req.body;

      if (!name || !price || !category_id) {
        return res.json({
          success: false,
          message: '商品名称、价格和分类不能为空'
        });
      }

      // 处理图片字段：支持单个URL字符串或JSON数组
      let imageValue = image;
      if (images && Array.isArray(images) && images.length > 0) {
        // 如果传入了images数组，使用它
        imageValue = JSON.stringify(images);
      } else if (image && typeof image === 'string') {
        // 如果是JSON字符串，保持不变；如果是单个URL，转换为数组格式
        try {
          JSON.parse(image); // 尝试解析，如果成功说明已经是JSON
          imageValue = image;
        } catch {
          // 不是JSON，单个URL转为数组格式
          imageValue = JSON.stringify([image]);
        }
      } else if (image && Array.isArray(image)) {
        // 如果直接是数组
        imageValue = JSON.stringify(image);
      }

      const [result] = await db.query(
        `INSERT INTO products (name, description, detail, price, category_id, image, stock, is_virtual, delivery_method, download_url, status, created_at, updated_at) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW())`,
        [name, description, detail, price, category_id, imageValue || null, stock, is_virtual, delivery_method, download_url || null]
      );

      logger.success('创建商品成功', { id: result.insertId, name });

      res.json({
        success: true,
        message: '创建成功',
        data: { id: result.insertId }
      });
    } catch (error) {
      logger.error('创建商品失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 更新商品（后台管理）
  async updateProduct(req, res) {
    try {
      const { id } = req.params;
      let { name, description, detail, price, category_id, image, images, stock, status, is_virtual, delivery_method, download_url } = req.body;

      const updates = [];
      const values = [];

      if (name !== undefined) {
        updates.push('name = ?');
        values.push(name);
      }

      if (description !== undefined) {
        updates.push('description = ?');
        values.push(description);
      }

      if (detail !== undefined) {
        updates.push('detail = ?');
        values.push(detail);
      }

      if (price !== undefined) {
        updates.push('price = ?');
        values.push(price);
      }

      if (category_id !== undefined) {
        updates.push('category_id = ?');
        values.push(category_id);
      }

      if (image !== undefined || images !== undefined) {
        let imageValue = image;
        if (images && Array.isArray(images) && images.length > 0) {
          imageValue = JSON.stringify(images);
        } else if (image && typeof image === 'string') {
          try {
            JSON.parse(image);
            imageValue = image;
          } catch {
            imageValue = JSON.stringify([image]);
          }
        } else if (image && Array.isArray(image)) {
          imageValue = JSON.stringify(image);
        }
        updates.push('image = ?');
        values.push(imageValue || null);
      }

      if (stock !== undefined) {
        updates.push('stock = ?');
        values.push(stock);
      }

      if (status !== undefined) {
        updates.push('status = ?');
        values.push(status);
      }

      if (is_virtual !== undefined) {
        updates.push('is_virtual = ?');
        values.push(is_virtual);
      }

      if (delivery_method !== undefined) {
        updates.push('delivery_method = ?');
        values.push(delivery_method);
      }

      if (download_url !== undefined) {
        updates.push('download_url = ?');
        values.push(download_url);
      }

      if (updates.length === 0) {
        return res.json({
          success: false,
          message: '没有要更新的内容'
        });
      }

      values.push(id);

      const [result] = await db.query(
        `UPDATE products SET ${updates.join(', ')}, updated_at = NOW() WHERE id = ?`,
        values
      );

      if (result.affectedRows === 0) {
        return res.json({
          success: false,
          message: '商品不存在'
        });
      }

      logger.success('更新商品成功', { id });

      res.json({
        success: true,
        message: '更新成功'
      });
    } catch (error) {
      logger.error('更新商品失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 删除商品（后台管理）
  async deleteProduct(req, res) {
    try {
      const { id } = req.params;

      // 检查是否有未完成的订单
      const [orders] = await db.query(
        'SELECT COUNT(*) as count FROM orders WHERE product_id = ? AND status = 0',
        [id]
      );

      if (orders[0].count > 0) {
        return res.json({
          success: false,
          message: '该商品存在未完成的订单，无法删除'
        });
      }

      const [result] = await db.query(
        'DELETE FROM products WHERE id = ?',
        [id]
      );

      if (result.affectedRows === 0) {
        return res.json({
          success: false,
          message: '商品不存在'
        });
      }

      logger.success('删除商品成功', { id });

      res.json({
        success: true,
        message: '删除成功'
      });
    } catch (error) {
      logger.error('删除商品失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }
}

module.exports = new ProductController();


